// signalr.js
import * as signalR from "@microsoft/signalr";

// let token = null;
// const storedToken = localStorage.getItem("jst:token");

// if (storedToken && storedToken.length > 7) {
//     token = storedToken.substring(7);
// }

const SignalR = {
    connection: null,

    initialize(url) {
        this.connection = new signalR.HubConnectionBuilder()
            .withUrl(url)
            .build();

        this.connection.onclose(() => {
            console.log('SignalR connection closed. Reconnecting...');
            this.startConnection();
        });

        this.startConnection();
    },

    startConnection() {
        this.connection.start().then(() => {
            console.log('SignalR connection established.');
        }).catch(err => {
            console.error('SignalR connection failed:', err.toString());
            setTimeout(() => this.startConnection(), 5000); // Retry after 5 seconds
        });
    },

    on(eventName, callback) {
        this.connection.on(eventName, callback);
    },

    off(eventName) {
        this.connection.off(eventName);
    },

    invoke(methodName, ...args) {
        return this.connection.invoke(methodName, ...args);
    },
     vaildConnectionAlive(){
        console.log("this.connection.state",this.connection.state)
        return this.connection.state===signalR.HubConnectionState.Connected
      }
};

export default SignalR;